// 各种依赖引入
import React from "react";
import ReactDOM from "react-dom";
import { inject, observer } from "mobx-react";
import { toJS } from 'mobx';
import { Button, Modal, Spin } from "antd";
import { WeaTop, WeaRightMenu, WeaTab, WeaLocaleProvider, WeaDialog, WeaFormItem, WeaSearchGroup } from "ecCom";
import { WeaSwitch, WeaTableNew, WeaLogView } from 'comsMobx';
import CreateAndEdit from "./createAndEdit";
const WeaLogViewComp = WeaLogView.Component;
const WeaTable = WeaTableNew.WeaTable;
const confirm = Modal.confirm;
const getLabel = WeaLocaleProvider.getLabel;

/*
  @inject 将组件连接到提供的 stores
  注入 store 到当前组件里，注入的 ("demo") 来源于 ../stores/index.js中的:
  module.exports = {
    demo: new demo()
  };
*/
@inject('demo')
// @observer 把组件变成响应式组件，以确保组件渲染中使用的数据变化时都可以强制刷新组件
@observer
class Home extends React.Component {
  constructor(props) {
    // 构造函数，用来实例化组件的初始熟悉
    super(props);
    this.state = {
      loading: true
    }
  }

  // 组件加载以后执行的方法，一般用来请求接口，初始化组件状态
  componentDidMount() {
    const { demo } = this.props;
    demo.doInit();
    this.setState({
      loading: false
    });
  }


  getAdvancedSearch = (form, datas, needTigger = true, col = 1, labelCol, fieldcol) => {
    const { isFormInit } = form;
    let group = [];
    const formParams = form.getFormParams();
    isFormInit && datas && datas.map(c => {
      let items = [];
      c.items.map(fields => {
        items.push({
          com: (<WeaFormItem
            label={`${fields.label}`}
            labelCol={{ span: labelCol || `${fields.labelcol}` }}
            wrapperCol={{ span: fieldcol || `${fields.fieldcol}` }}>
            <WeaSwitch fieldConfig={fields} form={form} formParams={formParams} />
          </WeaFormItem>),
          colSpan: 1
        })
      });
      if (needTigger) {
        group.push(<WeaSearchGroup col={col} needTigger={needTigger} title={c.title} showGroup={c.defaultshow} items={items} />)
      } else {
        group.push(<WeaSearchGroup col={col} needTigger={needTigger} showGroup={c.defaultshow} items={items} />)
      }
    });
    return group;
  }

  getTabButtonsAd = () => {
    const { demo } = this.props;
    const { searchForm } = demo;
    const btn = [
      (<Button type="primary"
        onClick={() => {
          demo.getTable(true);
          demo.setPanelStatus(false)
        }}>{getLabel(197, '搜索')}</Button>),
      (<Button onClick={() => { searchForm.resetForm() }}>{getLabel(2022, '重置')}</Button>),
      (<Button onClick={() => demo.setPanelStatus(false)}>{getLabel(31129, '取消')}</Button>),
    ];
    return btn;
  }

  onOperatesClick(record, index, operate) {
    const { demo } = this.props;
    let params = { id: record.id };
    demo.setCurrentId(record.randomFieldId);
    if (operate.index == '0') {
      this.doEdit(params);
    } else if (operate.index == '1') {
      demo.changeStatus(params);
    } else if (operate.index == '2') {
      demo.changeStatus(params);
    } else if (operate.index == '3') {
      this.showConfirm(getLabel(384757, '你确定要删除该记录吗?'), params);
    } else if (operate.index == '4') {
      this.log();
    }
  }

  batchDel = () => {
    const { demo } = this.props;
    const { tableStore } = demo;
    let params = toJS({ id: tableStore.selectedRowKeys });
    tableStore.selectedRowKeys.length > 0 && this.showConfirm(getLabel(384757, '你确定要删除该记录吗?'), params);
  }

  showConfirm(content, params) {
    let _this = this;
    confirm({
      title: getLabel(131329, '信息确认'),
      content: content || getLabel(384756, '你确定要删除选中的记录吗?'),
      okText: getLabel(33703, '确认'),
      cancelText: getLabel(31129, '取消'),
      onOk() {
        _this.onOk(params);
      },
      onCancel() {
        return false;
      },
    });
  }

  onOk(params) {
    const { demo } = this.props;
    demo.deleteRecord(params);
  }

  log() {
    const { demo } = this.props;
    demo.setLogVisible(true);
  }

  getLogParams() {
    let logType = '19';
    let logSmallType = '1';
    let params = {};
    const { demo } = this.props;
    if (demo.currentId) {
      params.id = demo.currentId;
    }
    if (demo.currentId) {
      let targetId = demo.currentId;
      return { logType, logSmallType, params, targetId };
    } else {
      return { logType, logSmallType, params };
    }
  }

  doEdit(record) {
    const { demo } = this.props;
    demo.setEditVisible(true);
    demo.editFormInit(record);
  }

  // 任何组件都必须有一个 render 方法用来渲染页面
  render() {
    const { demo } = this.props;
    const { form, editForm, visible, join, searchForm, inputValue, status, tableStore, logVisible, logStore, editVisible } = demo;
    const { showSearchAd, advancedSearchConditionInfo } = toJS(status);
    return (
      <div>
        <WeaLogViewComp
          visible={logVisible}
          onCancel={() => { demo.setLogVisible(false); demo.setCurrentId(''); }}
          logStore={logStore}
          {...this.getLogParams()}
        />
        <WeaTop
          title={getLabel(388226, "接入设置")}
          icon={<span style={{ fontWeight: "bold" }}>M</span>}
          iconBgcolor="#0079de"
          buttons={[
            <Button onClick={() => {
              demo.setVisible(true);
            }} type="primary">{getLabel(82, '新建')}</Button>,
            <Button onClick={() => {
              this.batchDel();
            }} type="primary">{getLabel(32136, '批量删除')}</Button>
          ]}
        />
        <Spin spinning={this.state.loading}>
          <WeaRightMenu
            collectParams={{
              favname: `${getLabel(388226, "接入设置")}`,
              favouritetype: 1,
              objid: 0,
              link: "wui/engine.html#/main/interface",
              importantlevel: 1
            }}
          >
            <WeaTab
              datas={[]}
              keyParam="viewcondition" //主键
              countParam="groupid" //数量
              //selectedKey={this.state.selectedKey}
              searchType="{['base','advanced']}"
              searchsBaseValue={inputValue}
              advanceHeight={120}
              searchsAd={this.getAdvancedSearch(searchForm, toJS(advancedSearchConditionInfo), false, 2)}
              showSearchAd={showSearchAd}
              buttonsAd={this.getTabButtonsAd()}
              setShowSearchAd={(bool) =>
                demo.setPanelStatus(bool)
              }
              hideSearchAd={() =>
                demo.setPanelStatus(false)
              }
              onChange={v => {
                // this.setState({ selectedKey: v });
                // searchForm.reset();
                // dataShowStore.setState({ selectedKey: v });
              }}
              onSearch={() => demo.getTable(true)}
              onSearchChange={value => {
                searchForm.updateFields({ em_name: value })
              }}
            >
            </WeaTab>
            {/* Table 列表 */}
            <WeaTable
              comsWeaTableStore={tableStore}
              hasOrder={true}
              needScroll={true}
              uniqueId={true}
              onOperatesClick={(record, index, operate) =>
                this.onOperatesClick(record, index, operate)}
            />
            {/* 引入 新建和编辑模块 */}
            <CreateAndEdit />
          </WeaRightMenu>
        </Spin>
      </div >
    );
  }
}

export default Home;
